#pragma once 
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include "util.hpp"
#include <mutex>
#include "log.hpp"
namespace ns_index
{
    struct DocInfo
    {
        std::string title; //标题
        std::string content; //去标签之后的内容
        std::string url; //官网文件url
        uint64_t doc_id; //文档的ID
    };
    struct InvertedElem
    {
        uint64_t doc_id;
        std::string word;
        int weight; //相关性
    };
    //倒排拉链
    typedef std::vector<InvertedElem> InvertedList;
    class Index
    {
    private:
        //单例模式
        Index(){};  //虽然是私有的，但是要有函数体，不能delete
        Index(const Index&) = delete;
        Index& operator=(const Index&) = delete;
        static Index* instance;
        static std::mutex mtx;
    public:
        static Index* GetInstance()
        {
            if(instance == nullptr)
            {
                mtx.lock();
                if(instance == nullptr)
                {
                    instance = new Index();
                }   
                mtx.unlock();
            }   
            return instance;
        }
    public:
        ~Index(){}
    public:
        //跟据doc_id找到文档内容
        DocInfo* GetForwardIndex(uint64_t doc_id)
        {
            if(doc_id >= forward_index.size())
            {
                std::cerr << "doc_id out range, error!" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }
        //跟据关键字string,获得倒排拉链
        InvertedList* GetInvertedList(const std::string& word)
        {
            std::unordered_map<std::string, InvertedList>::iterator iter = inverted_index.find(word);
            //auto iter = inverted_index.find(word); 
            if(iter == inverted_index.end())
            {
                std::cerr << word << " have no InvertedList " << std::endl;
                return nullptr;
            }
            return &iter->second;
        }
        //需要parser处理完毕后的数据，去用来构建正排和倒排索引
        bool BuildIndex(const std::string& input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if(!in.is_open())
            {
                std::cerr << "sorry, " << input << " open error" << std::endl;
            }
            std::string line;
            int count = 0; //记录一下当前是第几个了
            while(std::getline(in, line))
            {
                //正排
                DocInfo* doc = BuildForwardIndex(line);
                if(doc == nullptr)
                {
                    std::cerr << "build " << line << " error" << std::endl;
                    continue;
                }
                //倒排
                BuildInvertedIndex(*doc);
                count++;
                //if(count % 50 == 0)
                //{
                    //std::cout << "当前已创建的索引文档数：" << count << std::endl;
                    LOG(NORMAL, "当前已创建的索引文档数：" + std::to_string(count));
                //}
            }
        }
    private:
        //正排
        DocInfo* BuildForwardIndex(const std::string& line)
        {
            //1.解析，字符串的切分
            const std::string sep = "\3"; //行内分隔符
            std::vector<std::string> results;
            ns_util::StringUtil::Split(line, &results, sep);
            if(results.size() != 3)
            {
                return nullptr;
            }
            //2.字符串进行填充到DocInfo
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size(); //先保存id，在插入，doc_id刚好就是数组下标
            //3.插入到正排索引的vector
            forward_index.push_back(std::move(doc)); //doc里面是html，很大，直接写会拷贝，用move提高效率
            return &forward_index.back();
        }
        //倒排
        bool BuildInvertedIndex(const DocInfo& doc)
        {
            //DocInfo{title, content, url, doc_id}
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt()
                    : title_cnt(0)
                    , content_cnt(0)
                {}
            };
            std::unordered_map<std::string, word_cnt> word_map; //暂存词频映射表
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);
            for(std::string s : title_words)
            {
                boost::to_lower(s);
                word_map[s].title_cnt++; //这个单词在标题中出现的次数
            }
            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.content, &content_words);
            for(std::string s : content_words)
            {
                boost::to_lower(s);
                word_map[s].content_cnt++; //这个单词在内容中的出现次数
            }
#define X 10
#define Y 1
            for(std::pair<const std::string, word_cnt>& word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt; 
                
                InvertedList& inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }

        }
    private:
        //正排索引用数组
        std::vector<DocInfo> forward_index; //正排索引，因为数组天然就有下标
        //倒排索引一定是一个关键字和一组（个）InvertedElem对应
        std::unordered_map<std::string, InvertedList> inverted_index;//关键字和倒排拉链的映射关系
    };
    Index* Index::instance = nullptr;
    std::mutex Index::mtx;
}
